<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="create">创建用户</button>
    <button id="delete">删除用户</button>
    <button id="update">更新用户</button>
    <button id="query">查看单个用户</button>
    <button id="queryAll">查看所有用户</button>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
      /*     //设置基本的url
    axios.defaults.baseURL = 'http://localhost:3000'
    //批量设置请求头 common就是指针对所有的请求生效
    axios.defaults.headers.common['count']='1';
    //设置所有post请求的请求头
    axios.defaults.headers.post['age']='18'; */
      let createButton = document.querySelector("#create");
      let deleteButton = document.querySelector("#delete");
      let updateButton = document.querySelector("#update");
      let queryButton = document.querySelector("#query");
      let queryAllButton = document.querySelector("#queryAll");
      //添加请求的正常和失败的拦截器
      axios.interceptors.request.use((config)=>{
        //在此修改请求的配置对象，添加额外的请求头
        config.headers = {
            ...config.headers,
            'Content-Type':'application/json'
        }
        return config;
      },(error)=>{
        return Promise.reject(error);
        //return error;
      });
      //添加响应时的正常和失败的拦截器
      axios.interceptors.response.use((response)=>{
        //取出响应对象的data属性，向后传递
        return response.data;
      },(error)=>{
        //先看有没有response,如果有说明是响应出错了
        if(error.response){
            console.log(error.response)
            //如果有请求，说明请求出错，打印请求信息
        }else if(error.request){
            console.log(error.request)
        }else{//未知错误
            console.log(error)
        }
        return Promise.reject(error);
      });
      //相同的配置项可以在不同的地方设置，优先排序
      //调用时用户传的优化级最高>create创建实例时传的参数>默认值axios.defaults.baseURL
      createButton.addEventListener("click", () => {
        axios
          .post("/users", { name: "zhufeng2" })
          .then((response) => {
            console.log(response);
          })
      });
      queryButton.addEventListener("click", () => {
        axios
          .get("/users", { params: { id: 1 } })
          .then((response) => {
            console.log(response);
          })
      });
      updateButton.addEventListener("click", () => {
        axios
          .put("/users", { name: "updateZhufeng" }, { params: { id: 1 } })
          .then((response) => {
            console.log(response);
          })
      });
      deleteButton.addEventListener("click", () => {
        axios
          .delete("/users", { params: { id: 1 } })
          .then((response) => {
            console.log(response);
          })
      });
    </script>
  </body>
</html>
